from fastapi import APIRouter,Depends

from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.crud_pub.tb_project_message import get_name,query_data,add_data,delete_data,modify_data,clear_data,get_page_data,get_up_id,add_page,modify_page
from backend.app.app.models.effect_pridict.base_infomation import u_p_id,save_data,up_id,page_data

base_info_router = APIRouter(prefix="/base_info", tags=["1.单元措施规划方案基本信息"])

@base_info_router.post("/save_page",name="存储页面数据")
async def save_page(p_data:page_data,ver = Depends(verify_token_user)):  #
    user_pro_id = get_up_id()
    u_id = []
    p_id = []
    a = False
    for i in user_pro_id:
        if i[0] not in u_id:
            u_id.append(i[0])
        if i[1] not in p_id:
            p_id.append(i[1])
    if p_data.user_id in u_id:
        if p_data.proj_id in p_id:
            a = modify_page(userid=p_data.user_id,projid=p_data.proj_id,page_data=p_data.page,remark=p_data.remark)
        else:
            a =add_page(userid=p_data.user_id,projid=p_data.proj_id,data=p_data.page,remark=p_data.remark)
    else:
        a = add_page(userid=p_data.user_id, projid=p_data.proj_id, data=p_data.page, remark=p_data.remark)

    return {"result":a ,"verify":ver}

@base_info_router.post("/read_page",name="读取页面数据")
async def read_page(id:up_id,ver = Depends(verify_token_user)):
    re = get_page_data(user_id=id.user_id,proj_id=id.proj_id)

    return {"result":re,"verify":ver}

@base_info_router.post("/clear",name="清空数据表")
async def clear(ver = Depends(verify_token_user)):
    re = clear_data()
    return {"result":re,"verify":ver}

def create_tree(total_data, parent_unit_name, data_type):
    if data_type == "开发单元":
        belong_str, id_str, name_str, rank_str = "Belong_DvpUnit_Name", "DvpUnit_ID", "DvpUnit_Name", "DvpUnit_Rank"
    elif data_type == "措施":
        belong_str, id_str, name_str, rank_str = "Belong_StimType_Name", "StimType_ID", "StimType_Name", "StimType_Rank"
    tree = []
    try:
        for data in total_data:
            if data[rank_str] == "1":
                continue
            temp_dic = dict()
            if data[belong_str] == parent_unit_name:
                temp_dic['id'] = data[id_str]
                temp_dic['title'] = data[name_str]
                temp_dic['rank'] = data[rank_str]
                children = create_tree(total_data, data[name_str], data_type)
                if children:
                    temp_dic['children'] = children
                tree.append(temp_dic)
        return tree
    except Exception as e:
        print(e, e.__traceback__.tb_lineno)

def return_tree(datas, name):
    try:
        list = []
        for data in datas:
            if data['Belong_DvpUnit_Name'] == name:
                 list.append({
                    "id": data['DvpUnit_ID'],
                    "title": data['DvpUnit_Name'],
                    "rank": data['DvpUnit_Rank'],
                    "children": return_tree(datas, data['DvpUnit_Name'])
                 })
        for item in list:
            if len(item['children'])==0:
                del item['children']
        return list
    except Exception as e:
        print(e)

@base_info_router.post("/read_name",name="读取单元名称，方案名称")
async def read_name(ver = Depends(verify_token_user)):  #
    d_data,plan_infs = get_name()
    # d_name = return_tree(d_data, None)
    # 处理措施数据，生成树形结构
    dvp_tree = list()
    for data in d_data:
        temp_dic = dict()
        if data['DvpUnit_Rank'] == '1':
            temp_dic['id'] = data['DvpUnit_ID']
            temp_dic['title'] = data['DvpUnit_Name']
            children = create_tree(d_data, data['DvpUnit_Name'], "开发单元")
            if children:
                temp_dic['children'] = children
            dvp_tree.append(temp_dic)
    pro_name = []
    for plan in plan_infs:
        if plan[0] not in pro_name:
            pro_name.append(plan[0])
    return {"DvpUnit_Name": dvp_tree,"DvpUnit_OilStim_PlanProj_Name": pro_name, "verify": ver}

@base_info_router.post("/read_lib",name="读库")
async def read_lib(data:u_p_id,ver = Depends(verify_token_user)):
    re = query_data(dvpUnit_Name=data.DvpUnit_Name,PlanProj_Name=data.PlanProj_Name)

    return {"result":re,"verify":ver}

@base_info_router.post("/save_lib",name="存库")
async def save_lib(trans_data:save_data,ver = Depends(verify_token_user)):
    add_result=list()
    delete_result=list()
    modify_result=list()
    for data in trans_data.add:
        add_result.append(add_data(data))
    for data in trans_data.delete:
        delete_result.append(delete_data(data))
    for data in trans_data.modify:
        modify_result.append(modify_data(data))

    return {"add":add_result,"delete":delete_result,"modify":modify_result,"verify":ver}